package com.sciencep.pro.common.utils;

import com.sciencep.pro.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.ServletOutputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 文件流写入到TXT文本
 */
@Slf4j
public class TxtUtil {

    private TxtUtil() {

    }

    /**
     * 输出TXT
     *
     * @param outputStream
     * @param bytes
     */
    public static void writeToTxt(ServletOutputStream outputStream, byte[] bytes) throws CustomException {
        try (
                BufferedOutputStream buff = new BufferedOutputStream(outputStream);
        ) {
            buff.write(bytes);
            buff.flush();
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException e) {
            log.error("IOException", e);
            e.printStackTrace();
        }
    }

    /**
     * 写Txt
     *
     * @param list
     * @param path
     */
    public static void writeToTxt(List<?> list, String path) throws CustomException {

        String enter = "\r\n";
        StringBuilder write;

        try (
                FileOutputStream outSTr = new FileOutputStream(new File(path));
                BufferedOutputStream outputStream = new BufferedOutputStream(outSTr);
        ) {

            for (int i = 0; i < list.size(); i++) {
                write = new StringBuilder();
                write.append(list.get(i));
                write.append(enter);
                outputStream.write(write.toString().getBytes(StandardCharsets.UTF_8));
            }
            outputStream.flush();

        } catch (Exception e) {
            log.error("生成TXT文件失败:{}", e.getMessage());
            throw new CustomException("生成TXT文件失败");
        }


    }
}
